#include "mainpage.h"
#include "../utils/singleton.h"
#include "gatewayconfig.h"
#include "myprofile.h"
#include "net/mytcpsocket.h"
#include "serialport/myserialport.h"
#include "ui_mainpage.h"
#include <QCloseEvent>

MainPage::MainPage(QWidget *parent) : QWidget(parent), ui(new Ui::MainPage) {
  ui->setupUi(this);
  MYPROFILE_INIT(ui->TE_ProfileOut);
  // load config
  gw_config.reset(new GateWayConfig());
  qDebug() << QString("connected nums: %1")
                  .arg(gw_config->getConnectedList().length());
  for (const auto &[host, port] : gw_config->getConnectedList()) {
    ui->CB_SPortList->addItem(host);
  }
  ui->CB_SPortList->setCurrentText(gw_config->getLastConnected().first);
  //  ui->LE_Net_Port->setText(
  //      QString("%1").arg(gw_config->getLastConnected().second));

  // serialport
  ui->CB_SPortList->addItems(SG_SERIALPORT()->getPortLists());
  // socket
  connect(SG_TCPSOCKET(), &MyTcpSocket::connected, this,
          &MainPage::connectedSlot);
  connect(SG_TCPSOCKET(), &MyTcpSocket::disconnected, this,
          &MainPage::disconnectedSlot);
}

MainPage::~MainPage() { delete ui; }

////////////////////////////
/// Slots
////////////////////////////

void MainPage::connectedSlot() {
  MYPROFILE(ProfileType::TRACE, "服务器连接成功");
  ui->BT_Net_Connect->setEnabled(false);
  gw_config->setLastConnected(cur_connected);
}

void MainPage::disconnectedSlot() {
  MYPROFILE(ProfileType::TRACE, "服务器断开连接");
  ui->BT_Net_Connect->setEnabled(true);
}

void MainPage::serialErrorSlot(QSerialPort::SerialPortError serialPortError) {
  MYPROFILE(ProfileType::ERROR, QString("串口报错: %1").arg(serialPortError));
  SG_SERIALPORT()->close();
}

void MainPage::socketErrorSlot(QAbstractSocket::SocketError socketError) {
  MYPROFILE(ProfileType::ERROR, QString("服务器连接报错: %1").arg(socketError));
  SG_TCPSOCKET()->close();
}

////////////////////////////
/// Operation
////////////////////////////

void MainPage::on_BT_Net_Connect_clicked() {
  ui->BT_Net_Connect->setStyleSheet("qpushButton{background:rgb(0,225,0);}");
  SG_TCPSOCKET()->connectToHost(
      ui->CB_Net_IP->currentText(),
      static_cast<quint16>(ui->LE_Net_Port->text().toInt()));
  this->cur_connected = {ui->CB_Net_IP->currentText(),
                         ui->LE_Net_Port->text().toInt()};
}

void MainPage::on_BT_SPort_Open_clicked() {
  if (!SG_SERIALPORT()->isOpen()) {
    SG_SERIALPORT()->setPortName(ui->CB_SPortList->currentText());
    if (SG_SERIALPORT()->open(QIODevice::ReadWrite)) {
      MYPROFILE(ProfileType::TRACE, "打开串口");
      ui->BT_SPort_Open->setText("Close");
      ui->BT_SPort_Open->setStyleSheet("background: rgb(0,255,0)");
    }
  } else if (SG_SERIALPORT()->isOpen()) {
    MYPROFILE(ProfileType::TRACE, "关闭串口");
    SG_SERIALPORT()->close();
    ui->BT_SPort_Open->setText("Open");
    ui->BT_SPort_Open->setStyleSheet("");
  }
}

////////////////////////////
/// Test
////////////////////////////

void MainPage::on_BT_Test_Server_clicked() {
  // send
  double test_val = 1000.0;
  SG_TCPSOCKET()->send_sensor_data(SensorType::TEST_SEN, test_val);
  MYPROFILE(ProfileType::TRACE,
            QString("发送测试数据 '%1' 给服务器").arg(test_val));
}

#define TEST_STEP
void MainPage::on_BT_Test_Hard_clicked() {
  // LED test
#ifdef TEST_LED
  int light1 = rand() % 15;
  int light2 = rand() % 15;
  int light3 = rand() % 15;
  int light4 = rand() % 15;
  SG_SERIALPORT()->request_excute(ExcuteType::LED, (light1 << 8) | light2,
                                  (light3 << 8) | light4);
  MYPROFILE(ProfileType::TRACE, QString("发送测试数据 'LED 行1 亮度%1, "
                                        "行2 亮度%2, "
                                        "行3 亮度%3, "
                                        "行4 亮度%4' 给下位机")
                                    .arg(light1)
                                    .arg(light2)
                                    .arg(light3)
                                    .arg(light4));
#endif // TEST_LED
#ifdef TEST_FAN
  static bool fan_on = false;
  fan_on = !fan_on;
  SG_SERIALPORT()->request_excute(ExcuteType::FAN, fan_on ? 1.0 : -1.0);
  MYPROFILE(
      ProfileType::TRACE,
      QString("发送测试数据 '风扇 %1' 给下位机").arg(fan_on ? "打开" : "关闭"));
#endif // TEST_FAN
#ifdef TEST_RELAY
  static bool relay_on = false;
  static int relay_id = 0;
  relay_id++;
  relay_id = rand() % 2;
  relay_on = !relay_on;
  SG_SERIALPORT()->request_excute(ExcuteType::RELAY, relay_id == 1 ? 1.0 : -1.0,
                                  relay_on ? 1.0 : -1.0);
  MYPROFILE(ProfileType::TRACE, QString("发送测试数据  继电器%1号 %2")
                                    .arg(relay_id)
                                    .arg(relay_on ? "打开" : "关闭"));
#endif // TEST_RELAY
#ifdef TEST_STEP
  static bool is_on = false;
  is_on = !is_on;
  SG_SERIALPORT()->step_on(is_on);
  MYPROFILE(ProfileType::TRACE,
            QString("发送测试数据 步进电机 %2").arg(is_on ? "打开" : "关闭"));
#endif // TEST_STEP
}

////////////////////////////
/// Profile Message
////////////////////////////

void MainPage::on_BT_ClearMsg_clicked() { MYPROFILE_CLEAR(); }

void MainPage::on_BT_SaveFile_clicked() {}

void MainPage::on_BT_BrowseFile_clicked() {}

////////////////////////////
/// Event
////////////////////////////

void MainPage::closeEvent(QCloseEvent *ev) {
  ev->accept();
  gw_config->SaveToFile();
  singleton<MyTcpSocket>::getInstance(this)->close();
  singleton<MyTcpSocket>::getInstance(this)->deleteLater();
}

void MainPage::on_BT_SPort_Refresh_clicked() {
  ui->CB_SPortList->clear();
  ui->CB_SPortList->addItems(SG_SERIALPORT()->getPortLists());
}
